﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace RQX.Common.Web.Web.Container
{
    public class ApolloPlugClass
    {
        private readonly Type _classType = null;
        private readonly List<Type> _constructorTypes = null;
        private readonly ApolloPlug _plug = null;
        private object _instance = null;
        public ApolloPlugClass(ApolloPlug plug, Type classType, List<Type> constructorTypes)
        {
            _plug = plug;
            _classType = classType;
            _constructorTypes = constructorTypes;
            CreateInstance();
        }

        private void CreateInstance()
        {
            var paramters = new List<object>();
            foreach (var type in _constructorTypes)
            {
                var obj = _plug.GetClass(type.Name).GetInstance();
                paramters.Add(obj);
            }
            _instance = Activator.CreateInstance(_classType, paramters.ToArray());
        }

        public object GetInstance()
        {
            return _instance;
        }


        public ApolloPlugMethod GetMethod(string methodName)
        {
            if (_classType == null)
            {
                return null;
            }
            else
            {
                MethodInfo method = null;
                try
                {
                    method = _classType.GetMethod(methodName);
                }
                catch
                {
                    method = _classType.GetMethods().Where(k => k.Name.Equals(methodName)).FirstOrDefault();
                }
                if (method == null) return null;
                return new ApolloPlugMethod(method, _instance);
            }
        }
    }
}
